package com.leenleda.ips.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.leenleda.ips.BaseActivity;
import com.leenleda.ips.R;
import com.leenleda.ips.activity.adapter.ImageAdapter;
import com.leenleda.ips.databinding.ActivityImageBinding;
import com.leenleda.ips.entity.MarqueeEntity;
import com.leenleda.ips.entity.MediaEntity;
import com.leenleda.ips.receiver.Constant;
import com.leenleda.ips.util.FileUtils;
import com.leenleda.ips.util.GsonUtils;
import com.leenleda.ips.util.LogUtils;
import com.leenleda.ips.util.UShared;
import com.leenleda.ips.util.Utils;
import com.leenleda.ips.widget.DialogDownload;
import com.leenleda.ips.widget.banner.Banner;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ImageActivity extends BaseActivity implements Banner.OnListener {

    @Override
    public void conTrollShow(int state, String... data) {
        switch (state){
            case Constant.RELOAD_OPEN_TIME://开机5分钟后重新加载页面
                initData(1);
                break;
            case Constant.REFRESH_DOWNLOAD:
                if (dialog == null || data.length < 1)
                    return;
                int progress = Integer.parseInt(data[0]);
                LogUtils.e(tag,"---progress-----==" + progress);
                switch (progress){
                    case -1://下载失败
                        missDialog();
                        controlShow(1);
                        break;
                    case 100://下载成功
                        missDialog();
                        toPlayer();
                        break;
                    default://进度提示
                        dialog.update(progress);
                        break;
                }
                break;
            case Constant.PUSH_ROLL_MSG://显示滚动消息
                String msgData = data[0];
                MarqueeEntity bean = GsonUtils.getInstance().fromJson(msgData, MarqueeEntity.class);
                Log.e(tag, "==bundle===bean======" + bean);
                if (bean.getRollTime() < 1){
                    missRollMsg(true);
                    return;
                }
                showRollMsg(bean);
                break;
            case Constant.MISS_ROLL_MSG:
                Log.e(tag, "=====MISS_ROLL_MSG======" );
                missRollMsg(false);
                break;
            case Constant.DEVICE_PERMISSION_FALSE://提示到期
                LogUtils.e(tag, "-EVICE----false--" + data[0]);
                binding.tips.setVisibility(View.VISIBLE);
                binding.tips.setText(data[0]);
                break;
            case Constant.DEVICE_PERMISSION_TRUE:
//                ILog.e(tag, "-EVICE----true--" + data[0]);
                binding.tips.setVisibility(View.GONE);
                break;
            case Constant.INTERNET_CHANGE:
                binding.disconnect.setVisibility(Constant.NET_STATE ? View.GONE : View.VISIBLE);
                break;
            case Constant.CLEAR_ALL_CACHE:
                File file = new File(FileUtils.getPath(Constant.CACHE_FOLDER));
                FileUtils.deleteALl(file);
                break;
            case Constant.SET_MEDIA_DATA:
                LogUtils.e("SET_MEDIA_DATA", "====media=======" + data[0]);
                if (data[0].trim().equalsIgnoreCase(Constant.PUBLISH_WEB)) {
                    Utils.startActivity(this, new Intent(this, WebActivity.class));
                    finish();
                    return;
                }
                this.playState = 0;
                initData(2);
                return;
        }
    }

    private ActivityImageBinding binding;
    private List<MediaEntity> dataList = new ArrayList<>();
    private List<MediaEntity> listPic = new ArrayList<>();
    private List<MediaEntity> listVideo = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView( R.layout.activity_image);
        binding = (ActivityImageBinding) bindingView;
        LogUtils.e(tag,"---onCreate---: " + binding);
//        binding = DataBindingUtil.setContentView(this, R.layout.activity_image);
//        UShared.putLong(Constant.DEVICE_OPEN_TIME, System.currentTimeMillis() / 1000);
        binding.botL.setOnClickListener(v -> {
            missRollMsg(true);
        });
    }

    private boolean hasReload = false;
    @Override
    protected void onResume() {
        super.onResume();
        if (scanTime == 0){
            if (hasReload){
            } else {
                hasReload = true;
                new Handler().postDelayed(() -> conTrollShow(Constant.RELOAD_OPEN_TIME, "aa"), 2000);
            }
        } else
            controlShow(7);
        showTips("");
    }

    private void showTips(String data){
        String per = Utils.getStringValue(UShared.getString(Constant.DEVICE_PERMISSION_STATE));
        if (per.isEmpty()) {
            if (data.isEmpty())
                binding.tips.setVisibility(View.GONE);
            else {
                binding.tips.setText(data);
                binding.tips.setVisibility(View.VISIBLE);
            }
        } else {
            binding.tips.setText(per);
            binding.tips.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.e(tag,"---onPause---: " + binding);
        playState = 5;
        if (binding != null){
//            ILog.e(tag,"---onPause---22: " + binding.videoview.isPlaying());
            if (binding.videoview.isPlaying()){
                binding.videoview.pause();
            }
//            ILog.e(tag,"---onPause---33: " + binding.videoview.isPlaying());
        }
//        binding.videoview.suspend();
    }

    private List<String> videoList = new ArrayList<>();
    private int scanTime = 0;
    private void initData(int pos){
        boolean aa = checkPermission();
        String data = getData();
        String type = getType();
        LogUtils.e(tag, "==initData====checkPermission=" + aa + ",pos=" + pos);
        if (data.trim().isEmpty()){
            Utils.startActivity(this, new Intent(this, WebActivity.class));
            finish();
            return;
        }
        switch (type){
            case Constant.PUBLISH_SOURCE:
                break;
            case Constant.PUBLISH_WEB:
                Utils.startActivity(this, new Intent(this, WebActivity.class));
                finish();
                return;
            case Constant.PUBLISH_LIVE:
                Utils.startActivity(this, new Intent(this, LiveActivity.class));
                finish();
                return;
        }
        JsonParser parser = new JsonParser();
        JsonArray jArray = parser.parse(data).getAsJsonArray();
//        ILog.e(tag, "==jArray====" + jArray);
        dataList.clear();
        for (JsonElement obj : jArray)
            dataList.add(GsonUtils.getInstance().fromJson(obj, MediaEntity.class));
//        for (JsonElement obj : jArray){
//            MediaEntity entity = GsonUtils.getInstance().fromJson(obj, MediaEntity.class);
//            String ip = FileUtils.getServiceIp();
//            String path = "http://" + ip + ":1301/path/file/" + entity.getFilepath();
//            entity.setFilepath(path);
//            ILog.e(tag, "==EEEEEE==path=======" + path);
//            dataList.add(entity);
//        }
        //http://192.1.4.25:1301/path/file/
        //http://192.1.4.25:1301/path/file/materialFile/20210927143021/19/video_list.m3u8
        //materialFile/20210927143021/发热视频2.mp4
        //http://172.20.129.10:1301/path/file/materialFile/20220510082115/%E6%88%92%E7%83%9F.mp4
        //                                   materialFile/20220510082115/戒烟.mp4\

        listPic.clear();
        for (int i = 0; i < dataList.size(); i ++){
            MediaEntity entity = dataList.get(i);
//            entity.setFileName();//设置保存本地文件名字
            if (entity.getPosition() == -1)
                entity.setPosition(i);
            scanTime = Integer.parseInt(entity.getSwitchSpeed().isEmpty() ? "5" : entity.getSwitchSpeed());
//            String path = "http://192.168.5.101:1301/path/file/" + entity.getFilepath();
//            entity.setFilepath(path);
            if (entity.getFiletype() == 2)
                listPic.add(entity);
            else
                listVideo.add(entity);
            LogUtils.e(tag, "==EEEEEE==getFilepath=======" +entity.getFilepath() );
        }
        LogUtils.e(tag, "==EEEEEE==dataList=======" +dataList.size() );
        adapter = new ImageAdapter(this, listPic);
        binding.banner.setAdapter(adapter)
                .addBannerLifecycleObserver(this)//添加生命周期观察者
                .setLoopTime(scanTime * 1000)
                .setListener(this);
        controlShow(2);
    }

    private ImageAdapter adapter;

    @Override
    public boolean scrollPosition(int position) {
        curPos = listPic.get(position).getPosition();
        LogUtils.e(tag , "--************curPos*****11**********" + curPos + "==position==" + position);
        int upPos = position - 1;
        if (upPos < 0)
            upPos = listPic.size() - 1;
        int picUp = listPic.get(upPos).getPosition();
        int picThis = listPic.get(position).getPosition();
        LogUtils.e(tag , "==picUp==" + picUp + "===picThis==" + picThis + "==size==" + dataList.size() );

        if (listPic.size() == dataList.size())//当所有资源为图片时保持一直滚动
            return false;
        if (position == 0 && picUp != dataList.size() - 1){//当上一个不是所有dataList的最后一个时
            LogUtils.e(tag , "------picUp---------" + picUp );
            curPos = picUp;
            controlShow(3);
            return true;
        }

        int posFrom = picThis - picUp;
        if (picThis < picUp) {
            posFrom = picThis;
            curPos = -1;
        }

        if(posFrom > 1){
            if (curPos != -1)
                curPos = picUp;
            controlShow(4);
            return true;
        }
        return false;
    }

    private int curPos = -1;
    private void controlShow(int state){
        LogUtils.e(tag , "------controlShow--1----" + curPos + "(state:)" + state );
        if (Utils.dKey("image_Control"))
            return;
        curPos ++;
        LogUtils.e(tag , "------controlShow--2----" + curPos + "(state:)" + state );
        if (dataList.size() < 1)        //
            return;
        LogUtils.e(tag , "------controlShow---3---" + curPos + "(state:)" + state );
        if (curPos > (dataList.size() - 1))
            curPos = 0;
        LogUtils.e(tag , "--************curPos*****22**********" + curPos + "(state:)" + state );
        LogUtils.e(tag , "--************curPos*****22*********3*" + dataList.get(curPos).getFiletype() + "(getPath:)" + dataList.get(curPos).getPath() );
        if (dataList.get(curPos).getFiletype() == 2){
            binding.banner.start();
            binding.showVideo.setVisibility(View.GONE);
            if (listPic.size() == 1)
                new Handler().postDelayed(() -> controlShow(8), scanTime * 1000);
        } else {
            LogUtils.e(tag , "--------------播放视频------------------" + curPos);
            binding.banner.stop();
            entity = dataList.get(curPos);
            toPlayer();
        }
    }

    private MediaEntity entity = null;
    private void toPlayer() {
        if (entity == null)
            return;
        if (isDestroyed())
            return;
        Log.e(tag, "=====playState======" + playState);
        if (playState == 4) //正在播放中
            return;
        String fiMp4 = FileUtils.getVideoUrl(entity, ".mp4");
        Log.e(tag, "=====fiMp4======" + fiMp4 );
        if (!TextUtils.isEmpty(Utils.getStringValue(fiMp4))){
            binding.rlLoading.setVisibility(View.VISIBLE);
            binding.showVideo.setVisibility(View.VISIBLE);
            mVideoSource = fiMp4;
            Log.e(tag, "=====mVideoSource======" + mVideoSource);
            play();
            return;
        }
        boolean isOK = FileUtils.checkSize(entity);
//        Log.e(tag, "=====isOK======" + isOK);
        if (isOK){
            showDownload(entity);
        } else {
            handler.post(()->showTips("文件过大，内存空间不足"));
        }
    }

    private String mVideoSource = "";
    private void play(){
        LogUtils.e(tag, "-showPlayer----state----1--" + playState);
        switch (playState) {
            case 0:
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                initMediaPlayer();
                playState = 4;
                seedTo();
                binding.videoview.start();
                binding.rlLoading.setVisibility(View.GONE);
                break;
            case 4:
                playState = 0;
                binding.videoview.pause();
                play();
                break;
            case 5:
                playState = 4;
                seedTo();
                binding.videoview.start();
                binding.rlLoading.setVisibility(View.GONE);
                break;
            case 9:
                binding.videoview.setVideoPath(mVideoSource);
                seedTo();
                binding.videoview.start();
                binding.rlLoading.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 记录播放位置
     */
    private int mLastPos = 0;

    private void seedTo(){
        if (mLastPos > 0) {
            binding.videoview.seekTo(mLastPos);
            mLastPos = 0;
        }
    }

    /**
     * 状态：0，初始状态，3，播放器初始化完成(prepared)，4，播放中，
     * 5， 暂停中，8，播放完毕，9，播放错误
     */
    int playState = 0;
    private void initMediaPlayer() {
        binding.videoview.setVideoPath(mVideoSource);
        binding.videoview.setOnCompletionListener(mp -> {
            playState = 0;
            LogUtils.e(tag, "===setOnCompletionListener======");
            controlShow(6);
        });
        binding.videoview.setOnErrorListener((mp, what, extra) -> {
            LogUtils.e(tag, "===extra======" + extra);
            LogUtils.e(tag, "===what======" + what);
            mp.stop();
            playState = 0;
            controlShow(8);
            return true;
        });
    }

//***********=下载视频=*************

    private DialogDownload dialog;
    private void showDownload(MediaEntity entity){
        if (dialog == null)
            dialog = new DialogDownload(this);
        dialog.setListener(() ->  missDialog());
        dialog.show(entity);
    }

    private void missDialog(){
        LogUtils.e(tag,"---showDownload---dismiss: " + dialog);
        if (dialog == null)
            return;
        dialog.dismiss();
        dialog = null;
    }
}
